package com.labs;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * 循环遍历删除所有文件及文件夹
 */
public class DeleteFiles {
    public static void deleteFiles(String filePath, File[] listFiles){
        for(int i = 0 ; i < listFiles.length ; i ++) {
            File f = listFiles[i];
            String fName = f.getName();
            if (!f.isFile() && fName.equals("target")){
                try {
                    System.out.println("删除");
                    Files.walkFileTree(Path.of(filePath + File.separator + fName),
                            new SimpleFileVisitor<Path>() {
                                // 先去遍历删除文件
                                @Override
                                public FileVisitResult visitFile(Path file,
                                                                 BasicFileAttributes attrs) throws IOException {
                                    Files.delete(file);
                                    System.out.printf("文件被删除 : %s%n", file);
                                    return FileVisitResult.CONTINUE;
                                }
                                // 再去遍历删除目录
                                @Override
                                public FileVisitResult postVisitDirectory(Path dir,
                                                                          IOException exc) throws IOException {
                                    Files.delete(dir);
                                    System.out.printf("文件夹被删除: %s%n", dir);
                                    return FileVisitResult.CONTINUE;
                                }

                            }
                    );
                }catch (RuntimeException re){
                    re.printStackTrace();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
